package com.ics.cmsadmin.modules.agent.service.impl;

import com.ics.cmsadmin.frame.constant.Constants;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.agent.bean.AgentAccountBean;
import com.ics.cmsadmin.modules.agent.bean.AgentInfoBean;
import com.ics.cmsadmin.modules.agent.bean.ApplyWithdrawCashBean;
import com.ics.cmsadmin.modules.agent.enums.AccountChangesEnum;
import com.ics.cmsadmin.modules.agent.service.ApplyWithdrawCashService;
import com.ics.cmsadmin.modules.auth.bean.SysUser;
import com.ics.cmsadmin.modules.system.emums.RegisterKeyValueEnum;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Optional;

import static com.ics.cmsadmin.frame.constant.Constants.*;
import static com.ics.cmsadmin.modules.agent.steward.AgentRepositories.applyWithdrawCashDao;
import static com.ics.cmsadmin.modules.agent.steward.AgentServices.agentAccountService;
import static com.ics.cmsadmin.modules.agent.steward.AgentServices.agentInfoService;
import static com.ics.cmsadmin.modules.auth.steward.AuthServices.userService;
import static com.ics.cmsadmin.modules.system.steward.SystemServices.registerService;
@Service
public class ApplyWithdrawCashServiceImpl implements ApplyWithdrawCashService {


    @Override
    public boolean applyWithdrawCash(ApplyWithdrawCashBean bean, String loginUserId) {
        if (bean == null || bean.getWithdrawCash() == null || bean.getWithdrawCash().compareTo(new BigDecimal(0)) <= 0){
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL, "申请提现金额不能少于0");
        }
        AgentInfoBean agentInfoBean = agentInfoService.queryByUserId(loginUserId);
        if (agentInfoBean == null){
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL, "分销商不存在");
        }

        AgentAccountBean agentAccountBean = agentAccountService.queryByAgentNo(agentInfoBean.getAgentNo());
        if (agentAccountBean == null || bean.getWithdrawCash().compareTo(agentAccountBean.getBalance()) > 0){
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL,
                "提现金额" + bean.getWithdrawCash() + "元不得大于账户余额");
        }
//        int maxApplyWithdrawCashNum = registerService.queryRegisterValue(RegisterKeyValueEnum.APPLY_WITHDRAW_CASH_MAX_COUNT, Integer::valueOf);
//        if (maxApplyWithdrawCashNum >= 0 &&
//            applyWithdrawCashDao.count(ApplyWithdrawCashBean
//                .builder()
//                .agentNo(agentAccountBean.getAgentNo())
//                .status(Constants.APPLY_WITHDRAW_CASH_SUBMIT)
//                .build()) >= maxApplyWithdrawCashNum){
//            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL,
//                String.format("申请提现的次数不能超过%d次", maxApplyWithdrawCashNum));
//        }
        int applyWithdrawCashIntervalDay = registerService.queryRegisterValue(RegisterKeyValueEnum.APPLY_WITHDRAW_CASH_INTERVAL_DAY, Integer::valueOf);
        int maxAcceptWithdrawCashNum = registerService.queryRegisterValue(RegisterKeyValueEnum.WITHDRAW_CASH_INTERVAL_MAX_ACCEPT_COUNT, Integer::valueOf);
        long submitCount = applyWithdrawCashDao.count(ApplyWithdrawCashBean
            .builder()
            .agentNo(agentAccountBean.getAgentNo())
            .status(Constants.APPLY_WITHDRAW_CASH_SUBMIT)
            .build());
        if (applyWithdrawCashIntervalDay >= 0 &&
            maxAcceptWithdrawCashNum >= 0 &&
            applyWithdrawCashDao.count(ApplyWithdrawCashBean
                .builder()
                .agentNo(agentAccountBean.getAgentNo())
                .status(Constants.APPLY_WITHDRAW_CASH_ACCEPT_SUCCESS)
                .startUpdateTime(DateFormatUtils.format(DateUtils.addDays(new Date(), -maxAcceptWithdrawCashNum), "yyyy-MM-dd 00:00:00"))
                .build()) + submitCount >= maxAcceptWithdrawCashNum ){
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL,
                String.format("在%d天内,最多只能申请%d条提现申请", applyWithdrawCashIntervalDay, maxAcceptWithdrawCashNum));
        }
        BigDecimal minMoney = registerService.queryRegisterValue(RegisterKeyValueEnum.APPLY_WITHDRAW_CASH_MIN_MONEY, BigDecimal::new);
        if (minMoney.compareTo(bean.getWithdrawCash()) > 0){
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL,
                String.format("提现金额不得少于%s元", minMoney));
        }
        agentAccountService.accountChanges(agentInfoBean.getAgentNo(),
            bean.getWithdrawCash(),
            AccountChangesEnum.APPLY_WITHDRAW_CASH);
        bean.setAgentNo(agentInfoBean.getAgentNo());
        bean.setRemark("提现申请中。。。");
        return applyWithdrawCashDao.applyWithdrawCash(bean) == 1;
    }

    @Override
    public boolean acceptWithdrawCashApply(String applyId, String loginUserId) {
        if (StringUtils.isBlank(applyId)){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "申请提现id不能为空");
        }
        SysUser sysUser = userService.queryById(loginUserId);
        if (sysUser == null || !StringUtils.equals(USER_TYPE_ADMIN, sysUser.getUserType())) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该操作必须为管理员才能操作");
        }
        ApplyWithdrawCashBean applyWithdrawCashBean = applyWithdrawCashDao
            .findOne(ApplyWithdrawCashBean.builder().id(applyId).status(APPLY_WITHDRAW_CASH_SUBMIT).build());
        if (applyWithdrawCashBean == null){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "提现申请记录不存在或者已经处理");
        }
        try {
            agentAccountService.accountChanges(applyWithdrawCashBean.getAgentNo(),
                applyWithdrawCashBean.getWithdrawCash(),
                AccountChangesEnum.ACCEPT_WITHDRAW_CASH);
            return applyWithdrawCashDao.update(applyId, APPLY_WITHDRAW_CASH_ACCEPT_SUCCESS, "处理成功") == 1;
        }catch (CmsException e){
            return applyWithdrawCashDao.update(applyId, APPLY_WITHDRAW_CASH_ACCEPT_FAIL, e.getMessage()) == 1;
        }
    }

    @Override
    public boolean rejectWithdrawCashApply(String applyId, ApplyWithdrawCashBean bean, String loginUserId) {
        if (StringUtils.isBlank(applyId)){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "申请提现id不能为空");
        }
        SysUser sysUser = userService.queryById(loginUserId);
        if (sysUser == null || !StringUtils.equals(USER_TYPE_ADMIN, sysUser.getUserType())) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该操作必须为管理员才能操作");
        }
        ApplyWithdrawCashBean applyWithdrawCashBean = applyWithdrawCashDao
            .findOne(ApplyWithdrawCashBean.builder().id(applyId).status(APPLY_WITHDRAW_CASH_SUBMIT).build());
        if (applyWithdrawCashBean == null){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "提现申请记录不存在或者已经处理");
        }
        String remark = Optional.ofNullable(bean)
            .orElse(ApplyWithdrawCashBean.builder().remark("拒绝申请提现").build()).getRemark();
        agentAccountService.accountChanges(applyWithdrawCashBean.getAgentNo(),
            applyWithdrawCashBean.getWithdrawCash(),
            AccountChangesEnum.REFUSE_WITHDRAW_CASH);
        return applyWithdrawCashDao.update(applyId, APPLY_WITHDRAW_CASH_REJECT, remark) == 1;
    }

    @Override
    public boolean cancelWithdrawCashApply(String applyId, String loginUserId) {
        if (StringUtils.isBlank(applyId)){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "申请提现id不能为空");
        }
        AgentInfoBean agentInfoBean = agentInfoService.queryByUserId(loginUserId);
        if (agentInfoBean == null){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "登陆用户不是分销商，无法操作");
        }
        ApplyWithdrawCashBean applyWithdrawCashBean = applyWithdrawCashDao
            .findOne(ApplyWithdrawCashBean.builder().id(applyId).status(APPLY_WITHDRAW_CASH_SUBMIT).build());
        if (applyWithdrawCashBean == null || !StringUtils.equals(applyWithdrawCashBean.getAgentNo(), agentInfoBean.getAgentNo())){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "登陆分销商无法操作该提现申请");
        }
        agentAccountService.accountChanges(applyWithdrawCashBean.getAgentNo(),
            applyWithdrawCashBean.getWithdrawCash(),
            AccountChangesEnum.CANCEL_WITHDRAW_CASH);
        return applyWithdrawCashDao.update(applyId, APPLY_WITHDRAW_CASH_CANCEL, "分销商主动取消提现申请") == 1;
    }

    @Override
    public PageResult<ApplyWithdrawCashBean> listByLoginUserId(ApplyWithdrawCashBean bean,String loginUserId, PageBean pageBean) {
        return listByLoginUserId(bean, loginUserId, pageBean, applyWithdrawCashDao);
    }
}
